package main

import (
	"bufio"
	"bytes"
	"fmt"
	"log"
	"net"
	"os"
	"sync"
)

var (
	open  = make([]string, 0)
	close = make([]string, 0)
	wg    sync.WaitGroup
	wg2   sync.WaitGroup
	mu    sync.Mutex
)

var ports = make([]string, 0)
var IPS = make([]string, 0)

func main() {
	getIP()
	getPort()
	for _, ip := range IPS {
		wg2.Add(1)
		go func(ip string) {
			defer wg2.Done()
			for _, port := range ports {
				wg.Add(1)
				go func(ip, port string) {
					defer wg.Done()
					defer mu.Unlock()
					log.Println("扫描的对象：", ip+":"+port)
					_, err := net.Dial("tcp", ip+":"+port)
					mu.Lock()
					if err == nil {
						open = append(open, port)
					} else {
						close = append(close, port)
					}
				}(ip, port)
			}
			wg.Wait()
			for _, port := range open {
				log.Println(ip, ":", "开启的端口是---：", port)
			}
			for _, port := range close {
				log.Println(ip, ": ", "关闭的端口是：", port)
			}
		}(ip)
	}
	wg2.Wait()
}

func getPort() {
	fmt.Println("input Ports:(Such as: 11 22 33 80 443)")
	buf := make([]byte, 100)
	r := bufio.NewReader(os.Stdin)
	_, err := r.Read(buf)
	if err != nil {
		fmt.Println("getPort r.Read(buf)-->", err)
	}
	ports = cut(buf, ports)
}

func cut(buf []byte, res []string) []string {
	var sw int
	for n, v := range buf {
		if v == uint8(32) || v == uint8(44) || v == uint8(10) {
			res = append(res, string(buf[sw:n]))
			sw = n + 1
		}
		if v != uint8(32) {
			continue
		}
	}
	return res
}

func getIP() {
	fmt.Println("input IP:(Such as: 127.0.0.1)")
	buf := make([]byte, 50)
	c := make([]byte, 50)
	c[0] = uint8(10)
	r := bufio.NewReader(os.Stdin)
	_, err := r.Read(buf)
	if err != nil {
		fmt.Println("getIP Fscanf-->", err)
	}
	if bytes.Equal(buf, c) {
		IPS = []string{"127.0.0.1"}
	} else {
		IPS = cut(buf, IPS)
	}
}

func myerr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
